﻿// SMIL is a community project available under the Microsoft Public License (Ms-PL)
// Code is provided as is and with no warrenty – Use at your own risk
// View the project and the latest code at http://smil.codeplex.com/



using System;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using SMIL.Server.SPGeoRssCommonTypes;

namespace SMIL.Server.SPGeoRssCore
{
    public class SPGeoRssCore 
    {
        public static LayersResponse GetLayerList(SPWeb spWeb)
        {
            LayersResponse response = new LayersResponse();
            response.Layers = new System.Collections.Generic.List<LayerResponseObj>();

            foreach (SPList sp_list in spWeb.Lists)
            {
                if (sp_list.GetCoordinateLocation() != null)
                {
                    LayerResponseObj responseObj = new LayerResponseObj()
                    {
                        Name = sp_list.Title,
                        Path = sp_list.DefaultViewUrl,
                        Type = "SMIL",
                        ViewNames = sp_list.GetViews()
                        
                    };
                    response.Layers.Add(responseObj);
                }
            }
            return response;
        }

        public static GeoRss GenerateGeoRSS(SPWeb spWeb, SPList sp_list, SPView spView, string port)
        {

            //XmlNamespaceManager georssns = new XmlNamespaceManager(); //"http://www.georss.org/georss";
            //XNamespace georssns = "";

            if (spView == null)
            {
                spView = sp_list.DefaultView;
            }
            
            StringWriter sw = new StringWriter();
            XmlTextWriter w = new XmlTextWriter(sw);
            SPListItemCollection spListItemColl = sp_list.GetItems(spView);
            CoordinateLocation cl = sp_list.GetCoordinateLocation();
            
            string base_url = "http://" + (new Uri(spWeb.Url)).Host;

            base_url += port;

            w.WriteStartDocument();
            w.WriteStartElement("rss");
            w.WriteAttributeString("version", "2.0");
            w.WriteAttributeString("xmlns", "georss", null, "http://www.georss.org/georss");
            w.WriteAttributeString("xmlns", "gml", null, "http://www.opengis.net/gml");
            w.WriteAttributeString("xmlns", "media", null, "http://search.yahoo.com/mrss/");

            w.WriteStartElement("channel");
            w.WriteElementString("title", sp_list.Title);

            foreach (SPListItem item in spListItemColl)
            {
                w.WriteStartElement("item");

                w.WriteElementString("title", string.IsNullOrEmpty(sp_list.GetDisplayName(item.UniqueId)) ?
                    "Missing title" : sp_list.GetDisplayName(item.UniqueId));
     
                if (sp_list.BaseType == SPBaseType.DocumentLibrary)
                {
                    w.WriteElementString("link", base_url + item.File.ServerRelativeUrl);
                    w.WriteElementString("icon", base_url + "/_layouts/images/" + item.File.IconUrl.Replace(".gif", ".png"));

                    if (item.File.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                        w.WriteElementString("checkoutoverlay_url", base_url + "/_layouts/images/checkoutoverlay.png");
                }
                else
                {
                    w.WriteElementString("link", base_url + sp_list.RootFolder.ServerRelativeUrl + "/DispForm.aspx?ID=" + item.ID);

                    if (sp_list.BaseType != SPBaseType.GenericList || sp_list.BaseTemplate != SPListTemplateType.GenericList)
                        w.WriteElementString("icon", base_url + sp_list.ImageUrl.Replace(".gif", ".png"));
                    else
                        w.WriteElementString("icon", base_url + "/_layouts/images/swecopushpin.png");
                }

                w.WriteStartElement("style");
                w.WriteEndElement();

                GenerateDetailsSection(spView, item, cl, ref w);

                try
                {
                    string sPosition = item.GetCoordinate(cl);
                    string[] pieces = sPosition.Split(new char[] { ' ', '=' });
                    w.WriteElementString("point", "http://www.georss.org/georss", pieces[1] + " " + pieces[3]);
                }
                catch { }

                w.WriteEndElement();
            }

            w.WriteEndElement();

            w.WriteEndElement();
            w.Close();

            XmlDocument xd = new XmlDocument();
            xd.LoadXml(sw.ToString());

            sw.Close();
            sw.Dispose();

            GeoRss geoRss = new GeoRss()
            {
                Response = xd
            };

            return geoRss;
        }

        static void GenerateDetailsSection(SPView spView, SPListItem item, CoordinateLocation cl, ref XmlTextWriter w)
        {
            w.WriteStartElement("details");
            System.Collections.Specialized.StringCollection fieldNames = spView.ViewFields.ToStringCollection();
            foreach (var fieldName in fieldNames)
            {
                if (item.Fields.GetField(fieldName) != cl.Field)
                {
                    w.WriteStartElement("detail");
                    w.WriteAttributeString("fieldName", fieldName);
                    if (item[fieldName] != null)
                    {
                        w.WriteAttributeString("type", item[fieldName].GetType().ToString());
                        w.WriteValue(item.GetFormattedValue(fieldName));
                    }
                    else
                    {
                        SPField field = item.Fields.GetField(fieldName);
                        w.WriteAttributeString("type", field.GetType().ToString());
                    }

                    w.WriteEndElement();
                }
            }
            w.WriteStartElement("detail");
            w.WriteAttributeString("fieldName", "guid");
            w.WriteAttributeString("type", item.UniqueId.GetType().ToString());
            w.WriteValue(item.UniqueId.ToString());
            w.WriteEndElement();
            w.WriteEndElement();
        }

        public static ItemDetailResponse GenerateItemDetails(SPWeb spWeb, SPList sp_list, SPView spView, string item_guid)
        {
            if (spView == null)
            {
                spView = sp_list.DefaultView;
            }

            StringWriter sw = new StringWriter();
            XmlTextWriter w = new XmlTextWriter(sw);

            string base_url = "http://" + (new Uri(spWeb.Url)).Host;
            SPListItem item = sp_list.Items[new Guid(item_guid)];

            w.WriteStartDocument();

            GenerateDetailsSection(spView, item, sp_list.GetCoordinateLocation(), ref w);


            w.WriteEndDocument();
            w.Close();

            XmlDocument xd = new XmlDocument();
            xd.LoadXml(sw.ToString());

            sw.Close();
            ItemDetailResponse response = new ItemDetailResponse();

            response.SPItemDetail = new XmlDocument();
            response.SPItemDetail = xd;
            return response;
        }

        public static string GetRequestPort(string requestUrl)
        {
            string[] pieces = requestUrl.Split(new char[] { ':' });
            if (pieces.Length == 2)
                return string.Empty;

            string tail = pieces[2];
            return string.Format(":{0}", tail.Split(new char[] { '/' })[0] as string);
        }
    }
}
